import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/components/bigfontchoosebutton.dart';
import 'package:dio/dio.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/category/clothcategory.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/category/outfitcategory.dart';
import 'package:wayofdressing/dio/OutfitDio.dart';
import 'package:wayofdressing/good_method/show_dialog.dart';

class AddOutfitScreen extends StatefulWidget {
  const AddOutfitScreen({super.key});

  @override
  State<AddOutfitScreen> createState() => _AddOutfitScreenState();
}

class _AddOutfitScreenState extends State<AddOutfitScreen> {
  int whoisactive1 = 1;

  List<String> categories = [];
  TextEditingController _descriptionController = TextEditingController();
  TextEditingController _nameController = TextEditingController();
  TextEditingController _idController = TextEditingController();
  List<Widget> allWidgets = [];

  Future<void> addOutfitAndCloth() async {
    if (_nameController.text == '' ||
        _descriptionController.text == '' ||
        _idController.text == '') {
      ShowDialog.showErrorAndDetail(context, '输入不能为空!');
      return;
    }
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int userId = prefs.getInt('id') ?? 0;
      try {
        Response<dynamic> addOutfitResponse = await addOutfitByUserId(
          userId: userId,
          outfitData: {
            'name': _nameController.text,
            'description': _descriptionController.text,
            'category': categories[whoisactive1]
          },
          dio: dio,
        );
      } catch (e) {}
      Response<dynamic> addClothResponse =
          await addClothToOutfitByUserIdAndUserClothIdAndName(
        userId: userId,
        userClothId: int.parse(_idController.text),
        name: _nameController.text,
        dio: dio,
      );
      if (addClothResponse.statusCode != 200 ||
          addClothResponse.data['success'] != true) {
        ShowDialog.showError(context);
        throw Exception('Failed to add cloth to outfit');
      } else {
        isAdd = true;
        ShowDialog.showCorrect(context);
      }
    } catch (e) {
      print('Error in adding outfit and cloth: $e');
      ShowDialog.showError(context);
      throw e; // 可以选择重新抛出异常，或根据需要进行其他处理
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isAdd = false;
    categories = outfitNumbers.keys.toList();
    allWidgets = clothCategoryWidgetList.values.expand((list) => list).toList();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _descriptionController.dispose();
    _nameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 40.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Expanded(
                flex: 7,
                child: ListView.builder(
                    scrollDirection: Axis.vertical,
                    itemCount: allWidgets.length,
                    itemBuilder: (context, index) {
                      return allWidgets[index];
                    }),
              ),
              Expanded(
                flex: 5,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.only(bottom: 6,top: 10),
                        height: 48,
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                              spreadRadius: 2, // 阴影扩展半径
                              blurRadius: 5, // 阴影模糊半径
                              offset: Offset(0, 5), // 阴影偏移量
                            ),
                          ],
                          borderRadius: BorderRadius.circular(25),
                          color: Colors.white,
                        ),
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: clothSubCategories.length,
                          itemBuilder: (context, index) {
                            return BigFontChooseButton(
                              isActive: whoisactive1,
                              text: categories[index],
                              listNumber: index,
                              onPressed: () {
                                setState(() {
                                  whoisactive1 = index;
                                });
                              },
                            );
                          },
                        ),
                      ),
                    ),
                    Expanded(
                      child: Row(
                        children: [
                          Expanded(
                            child: TextField(
                              controller: _idController,
                              decoration: InputDecoration(
                                labelText: '衣服ID',
                                labelStyle:
                                    TextStyle(fontSize: 20, color: Colors.grey),
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0),
                                  borderSide:
                                      BorderSide(width: 2, color: Colors.grey),
                                ),
                                focusedBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0),
                                  borderSide:
                                      BorderSide(width: 2, color: Colors.black),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Expanded(
                      child: Row(
                        children: [
                          Expanded(
                            child: TextField(
                              controller: _nameController,
                              decoration: InputDecoration(
                                labelText: '搭配名称',
                                labelStyle:
                                    TextStyle(fontSize: 20, color: Colors.grey),
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0),
                                  borderSide:
                                      BorderSide(width: 2, color: Colors.grey),
                                ),
                                focusedBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0),
                                  borderSide:
                                      BorderSide(width: 2, color: Colors.black),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Expanded(
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(
                            child: TextField(
                              controller: _descriptionController,
                              decoration: InputDecoration(
                                labelText: '搭配描述',
                                labelStyle:
                                    TextStyle(fontSize: 20, color: Colors.grey),
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0),
                                  borderSide:
                                      BorderSide(width: 2, color: Colors.grey),
                                ),
                                focusedBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0),
                                  borderSide:
                                      BorderSide(width: 2, color: Colors.black),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.only(bottom:12,top: 3),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(25), // 圆角半径
                          border: Border.all(
                            // 边框
                            color: Colors.black54, // 边框颜色
                            width: 2, // 边框宽度
                          ),
                        ),
                        child: TextButton(
                          child: Text(
                            '添加',
                            style: TextStyle(
                                color: Colors.black54, fontSize: 30),
                          ),
                          onPressed: addOutfitAndCloth,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
